<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
class Admin_Model_Util_Grid{
    const STRING_TYPE = 'string';
    const LIST_TYPE = 'list';
    const NUMERIC_TYPE = 'numeric';
    const BOOLEAN_TYPE = 'boolean';

    static function toOrderSQL($sort){
        $sort = str_replace("\\", "", $sort);
        $order = Zend_Json::decode($sort);
        $result = array();
        foreach ($order as  $item){
            $result[]=$item['property']." ".$item['direction'];
        }
        return $result;
    }
    static function toFiltersSQL($filter){
        if (empty($filter)) return null;
        $filter = str_replace("\\", "", $filter);       
        $filter = Zend_Json::decode($filter);
        $filterResult = array();        
        $db =  Zend_Registry::get('DB');        
        foreach ($filter as $item){
           if ($item['type'] == self::STRING_TYPE){
               $filterResult[] = $db->quoteInto("{$item['field']} like ?", "%{$item['value']}%");
           }elseif($item['type'] == self::LIST_TYPE){
               $strTmp = "";
               if (is_string($item['value'])){
                   $item['value'] = explode(",",$item['value']);
               }               
               foreach ($item['value'] as $value){
                   $strTmp .= $item['field'] . "=" . "'$value'";
                   if (end($item['value']) != $value) $strTmp .= " or ";
               }
               $filterResult[] = $strTmp;
           }elseif($item['type'] == self::NUMERIC_TYPE){
               if($item['comparison'] == 'lt') $comparison = "<";
               elseif($item['comparison'] == 'gt') $comparison = ">";
               else $comparison = "=";
               $filterResult[] = $db->quoteInto("{$item['field']} {$comparison} ?", "{$item['value']}");
           }elseif($item['type'] == self::BOOLEAN_TYPE){
               $value = $item['value']=='true' ? 1 : 0;
               $filterResult[] = $db->quoteInto("{$item['field']} = ?", "{$value}");
           } 
        }        
        return $filterResult;
    }
}
?>
